package com.luych.userCenter.service;

import com.luych.common.constant.SpringCacheConstant;
import com.luych.common.constant.UserMessageConstant;
import com.luych.userCenter.dao.PermissionInfoMapper;
import com.luych.userCenter.dao.RoleInfoMapper;
import com.luych.userCenter.dao.RoleRPermissionMapper;
import com.luych.userCenter.dao.UserRRoleMapper;
import com.luych.userCenter.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class AuthorizationService {

    private final RoleInfoMapper roleDao;
    private final PermissionInfoMapper permissionDao;
    private final UserRRoleMapper userRRoleDao;
    private final RoleRPermissionMapper roleRPermissionDao;

    @Autowired
    public AuthorizationService(RoleInfoMapper roleDao, PermissionInfoMapper permissionDao, UserRRoleMapper userRRoleDao, RoleRPermissionMapper roleRPermissionDao) {
        this.roleDao = roleDao;
        this.permissionDao = permissionDao;
        this.userRRoleDao = userRRoleDao;
        this.roleRPermissionDao = roleRPermissionDao;
    }

    @Cacheable(cacheNames = SpringCacheConstant.userProvider_userPermissions, key = "userId")
    public List<PermissionInfo> getPermissionsByUserId(String userId) {
        UserRRoleExample userRRoleExample = new UserRRoleExample();
        userRRoleExample.or().andUserIdEqualTo(userId);
        List<UserRRole> userRRoles = userRRoleDao.selectByExample(userRRoleExample);
        Set<String> permissionIds = new HashSet<>();
        List<PermissionInfo> permissionInfos = new ArrayList<>();
        for (UserRRole userRRole : userRRoles) {
            RoleRPermissionExample roleRPermissionExample = new RoleRPermissionExample();
            roleRPermissionExample.or().andRoleIdEqualTo(userRRole.getRoleId());
            List<RoleRPermission> roleRPermissions = roleRPermissionDao.selectByExample(roleRPermissionExample);
            for (RoleRPermission roleRPermission : roleRPermissions) {
                if (!permissionIds.contains(roleRPermission.getPermissionId())) {
                    PermissionInfo permissionInfo = permissionDao.selectByPrimaryKey(roleRPermission.getPermissionId());
                    permissionInfos.add(permissionInfo);
                    permissionIds.add(roleRPermission.getPermissionId());
                }

            }
        }
        return permissionInfos;
    }

    public void addRole(RoleInfo roleInfo) {
        roleDao.insertSelective(roleInfo);
    }

    public void modifyRole(RoleInfo roleInfo) {
        roleDao.updateByPrimaryKeySelective(roleInfo);
    }

    public void deleteRole(String roleId) {
        roleDao.deleteByPrimaryKey(roleId);
        
        
    }


}
